<script lang="ts" setup>
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { onMounted, onUnmounted, ref } from 'vue';
import { VOLUME_TYPE } from '@/enums/device.enums';
import { useDeviceSetting } from '@/hooks/useDeviceSetting';
import { useSpeakQueue } from '@/hooks/useSpeakQueue';
import { useDeviceStore } from '@/store/deviceStore';
import { useThemeStore } from '@/store/themeStore';
import { getAppVersion } from '@/utils';

const buildTime = dayjs(__VITE_APP_BUILD_TIME__).format('YYYY-MM-DD HH:mm:ss');

const deviceStore = useDeviceStore();
const { deviceCode, deviceAttrs } = storeToRefs(deviceStore);

const { setBrightness, setVolume } = useDeviceSetting();

const themeStore = useThemeStore();
const { theme, themeOptions } = storeToRefs(useThemeStore());

const { version, versionCode } = getAppVersion();

// 设置表单数据
const formData = ref({
  themeColor: theme.value, // 默认主题色
  deviceCode: deviceCode.value, // 设备编码
  tts: '这是一段语音测试内容',
  ...deviceAttrs.value
});

// 播报次数选项
const speakTimesOptions = [
  { value: 1, label: '1次' },
  { value: 2, label: '2次' },
  { value: 3, label: '3次' }
];

// 滚动速度选项
const scrollSpeedOptions = [
  { value: 0.5, label: '0.5x' },
  { value: 1, label: '1x' },
  { value: 2, label: '2x' }
];

const { addToSpeakQueue, initSpeakQueue, destroySpeakQueue } = useSpeakQueue();

function onTestTTS() {
  addToSpeakQueue({
    text: formData.value.tts,
    repeat: deviceAttrs.value.speakTimes
  });
}

// 保存设置
function saveSettings() {
  if (!formData.value.deviceCode) {
    uni.showToast({
      title: '请输入设备编码',
      icon: 'error'
    });
    return;
  }

  // 更新设备编码
  deviceStore.setDeviceCode(formData.value.deviceCode);

  deviceStore.setDeviceAttrs(formData.value);

  // 更新主题色
  themeStore.setTheme(formData.value.themeColor);

  uni.showToast({
    title: '保存成功',
    icon: 'success'
  });
}

// 返回上一页
function goBack() {
  uni.navigateBack();
}

function handleBrightnessChange({ value }: { value: number }) {
  setBrightness(value);
}

function handleVolumeChange({ value }: { value: number }) {
  setVolume(value, VOLUME_TYPE.VOLUME_TYPES_MEDIA);
}

onMounted(() => {
  console.log('设置组件初始化');
  initSpeakQueue();
});

onUnmounted(() => {
  console.log('设置组件销毁');
  destroySpeakQueue();
});
</script>

<template>
  <view class="setting-container">
    <wd-navbar title="设置" fixed />
    <view class="setting-content">
      <!-- 版本号信息 -->
      <view class="setting-item version-item">
        <view class="version-info">
          <view class="version-title">
            版本信息
          </view>
          <view class="grid grid-cols-2">
            <view class="version-details">
              <text class="version-label">
                版本号：
              </text>
              <text class="version-value">
                {{ version }}
              </text>
            </view>
            <view class="version-details">
              <text class="version-label">
                构建号：
              </text>
              <text class="version-value">
                {{ versionCode }}
              </text>
            </view>
            <view class="version-details">
              <text class="version-label">
                构建日期：
              </text>
              <text class="version-value">
                {{ buildTime }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 设备编码设置 -->
      <view class="setting-item">
        <view class="setting-item-title">
          设备编码
        </view>
        <wd-input
          v-model="formData.deviceCode"
          size="large"
          placeholder="请输入设备编码"
          clearable
        />
      </view>

      <view class="setting-item">
        <view class="setting-item-title">
          服务器地址
        </view>
        <wd-input
          v-model="formData.serverUrl"
          size="large"
          placeholder="请输入设备编码"
          clearable
        />
      </view>

      <view class="setting-item">
        <view class="setting-item-title">
          Websocket地址
        </view>
        <wd-input
          v-model="formData.websocketUrl"
          size="large"
          placeholder="请输入设备编码"
          clearable
        />
      </view>

      <view class="setting-item">
        <view class="setting-item-title">
          MQTT地址
        </view>
        <wd-input
          v-model="formData.mqttUrl"
          size="large"
          placeholder="请输入设备编码"
          clearable
        />
      </view>

      <!-- 主题色设置 -->
      <view class="setting-item">
        <view class="setting-item-title">
          主题色
        </view>
        <view class="theme-colors">
          <view
            v-for="color in themeOptions"
            :key="color.value"
            class="color-item"
            :class="{ active: formData.themeColor === color.value }"
            @click="formData.themeColor = color.value"
          >
            <view class="color-preview" :style="{ backgroundColor: color.value as string }">
              <view v-if="formData.themeColor === color.value" class="color-check">
                <text class="iconfont icon-check" />
              </view>
            </view>
            <text class="color-name">
              {{ color.label || '默认' }}
            </text>
          </view>
        </view>
      </view>

      <!-- 语音播报次数设置 -->
      <view class="setting-item">
        <view class="setting-item-title">
          语音播报次数
        </view>
        <wd-radio-group v-model="formData.speakTimes" shape="button">
          <wd-radio
            v-for="option in speakTimesOptions"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </wd-radio>
        </wd-radio-group>
      </view>

      <view class="setting-item">
        <view class="setting-item-title">
          滚动速度
        </view>
        <wd-radio-group v-model="formData.scrollSpeed" shape="button">
          <wd-radio
            v-for="option in scrollSpeedOptions"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </wd-radio>
        </wd-radio-group>
      </view>

      <!-- 亮度设置 -->
      <view class="setting-item">
        <view class="setting-item-title">
          亮度
        </view>
        <view class="slider-container">
          <wd-slider
            v-model="formData.brightness"
            class="flex-1"
            :min="0"
            :max="100"
            :step="1"
            @dragmove="handleBrightnessChange"
          />
        </view>
      </view>

      <!-- 播报音量设置 -->
      <view class="setting-item">
        <view class="setting-item-title">
          播报音量
        </view>
        <view class="slider-container">
          <wd-slider
            v-model="formData.volumeMedia"
            class="flex-1"
            :min="0"
            :max="10"
            :step="1"
            @dragmove="handleVolumeChange"
          />
        </view>
      </view>

      <!-- 息屏时间设置 -->
      <view class="setting-item">
        <view class="setting-item-title">
          息屏时间
        </view>
        <wd-datetime-picker v-model="formData.screenOffTime" type="time" label="选择时间段" use-second />
      </view>

      <!-- TTS语音测试 -->
      <view class="setting-item">
        <view class="setting-item-title">
          TTS语音测试
        </view>
        <wd-input
          v-model="formData.tts"
          size="large"
          placeholder="请输入TTS语音测试内容"
        >
          <template #suffix>
            <wd-button type="primary" @click="onTestTTS">
              测试
            </wd-button>
          </template>
        </wd-input>
      </view>

      <!-- 按钮组 -->
      <view class="button-group">
        <wd-button type="info" size="large" @click="goBack">
          返回
        </wd-button>
        <wd-button type="primary" size="large" @click="saveSettings">
          保存
        </wd-button>
      </view>
    </view>
  </view>
</template>

<route lang="json5">
{
  layout: 'none',
  style: {
    navigationStyle: 'custom'
  }
}
</route>

<style lang="scss" scoped>
.setting-container {
  background-color: #f7f8fa;
  height: 100%;
  overflow: auto;
}

.setting-content {
  padding: 20px;
  margin-top: 60px;
}

.setting-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.version-item {
  display: flex;
  flex-direction: column;
}

.version-info {
  padding: 10px 0;
}

.version-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
}

.version-details {
  display: flex;
  align-items: center;
  flex-direction: row;
  margin-bottom: 10px;
}

.version-label {
  color: #666;
  font-size: 16px;
  width: 120px;
}

.version-value {
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.setting-item-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
}

.theme-colors {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  gap: 30px;
}

.color-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  width: 80px;
  position: relative;

  &.active .color-preview {
    transform: scale(1.15);
    box-shadow:
      0 0 0 2px #fff,
      0 0 0 4px var(--main-color, #2177ff);
  }

  &.active .color-name {
    color: var(--main-color, #2177ff);
    font-weight: 500;
  }

  &.active::after {
    content: '';
    position: absolute;
    top: -5px;
    right: -5px;
    width: 20px;
    height: 20px;
    background-color: var(--main-color, #2177ff);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  &.active::before {
    content: '✓';
    position: absolute;
    top: -5px;
    right: -5px;
    width: 20px;
    height: 20px;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 12px;
  }
}

.color-preview {
  width: 50px;
  height: 30px;
  border-radius: 4px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  margin-bottom: 8px;
}

.color-name {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.color-check {
  color: #fff;
  font-size: 24px;
  text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
}

.slider-container {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.slider-value {
  margin-left: 15px;
  min-width: 30px;
  text-align: right;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;

  .wd-button {
    width: 45%;
  }
}

// 调整单选按钮组的布局
:deep(.wd-radio-group) {
  display: flex;
  flex-direction: row;

  .wd-radio {
    margin-right: 20px;
  }
}
</style>
